package yxy.game.pm2.active.module.sdk.shengye;

import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import yxy.apple.http.HTTPConnection;
import yxy.apple.http.request.JSONRequest;
import yxy.apple.http.response.JSONResponse;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.game.pm2.bean.sdk.WeiXinOtherParm;

import java.util.Map;

public class ShengYeSubscribeHandle {

	// 时间控制===========================================================================

	public void update() {
		long now = DateTime.now().getMillis();

		// 发送订阅
		try {
			if (ShengYeSubscribeModule.lockShengYeSubscribe()) {
				Map<String, Long> smap = ShengYeSubscribeModule.all();
				if (smap != null && smap.size() != 0) {
					System.out.println("shegnye jinru");
					for (String key : smap.keySet()) {
						long times = smap.get(key);
						if (times == 0) {
							continue;
						}

						if (now < times) {
							continue;
						}

						ShengYeSubscribeModule.touch().put(key, Long.valueOf(0));
//						smap.put(key, Long.valueOf(0));
						subscribe1(key);
//						ShengYeSubscribeModule.all().put(key, (long) 0);

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ShengYeSubscribeModule.unlockShengYeSubscribe();
		}

	}

	private static final String subscribeurl = "http://docater1.cn/index.php?g=Wap&m=MiniGame&a=send_tpl_msg_touser";
	private static final int type1 = 1;	
	private static final int type2 = 2;	
	
	private void subscribe1(String playercode) throws Exception{
		
//		参数名称 说明 是否必传
//		openid ⽤户的openid 是
//		channel channel_id 是
//		tpl_type 活动分类：1离线收益提醒；	2活动提醒；
//		是
//		template_id 模版ID 是
//		page 路径，例：index?tpl_type=1 (tpl_type与上⽅传参⼀致，tpl_type是为了统计当
//		前订阅消息所属分类
		
		WeiXinOtherParm wxop = WeiXinOtherParm.get(playercode);
		if(wxop == null) {
			return;
		}
		
		JSONObject json = new JSONObject();
		json.put("openid", wxop.getOpenid());
		json.put("channel", SDKParm.getSdkparmvalue(SdkParmEnum.shengye_gamekey));
		json.put("tpl_type", type1);
		json.put("template_id", "ER4MAeQZ4bAeuRjQ8gadMQsLH1mYLtyxu6GU1BUATc4");
		json.put("page", "index?tpl_type=" + type1);
		
//		System.out.println("sehngye " + json);
		try {
			JSONObject syretjson = response(subscribeurl, 30000, json);
			System.out.println("shengye " + syretjson);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	public static JSONObject response(String url, int timeout, JSONObject body) throws Exception {
		HTTPConnection connection = null;
		try {
			connection = new HTTPConnection(timeout);
			JSONRequest jsonRequest = new JSONRequest(url);
			jsonRequest.setHeader("Content-Type", "application/json");
			jsonRequest.setBody(body);
			JSONResponse response = connection.request(jsonRequest, JSONResponse.class);
			
			JSONObject result = response.body();
			return result;
		} catch (Exception e) {
			throw e;
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
	}
}
